package de.xXephis.MeineMensa;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;

import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.*;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

import de.xXephis.MeineMensa.XMLEntity.XMLDayPOJO;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;


public class XMLProvider {
	 private static final String phurl = "http://meine-mensa.de/speiseplan_gadget?day=[d]&year=[y]&month=[m]&location_id=[l]";
	 private DefaultHttpClient client = new DefaultHttpClient();
	 private Context context=null;
	 public static final int OPTION_FORCE = 1;
	 public static final int OPTION_CACHE = 2;
	 
	 public XMLProvider(Context c) {
		this.context=c;
	}
	 
	 public XMLDayPOJO getDay(String d, String m, String y, String l, int option) throws Exception
	 {
		 String url=phurl;
		 url=url.replace("[d]", d);
		 url=url.replace("[m]", m);
		 url=url.replace("[y]", y);
		 url=url.replace("[l]", l);
		 Log.d("getDay.url", url);
		 return getObject(url, option);
	 }
	 
	 private XMLDayPOJO getObject(String url, int option) throws Exception
	 {
		 String plainXML=getPlainXMLString(url, option);
		 if(plainXML == null)
			 return null;
		 
		 plainXML=plainXML.replaceAll("><", ">\r\n<");
		 plainXML=plainXML.replaceAll("<script/>", "");
		 Serializer serializer = new Persister();  
		 Reader reader = new StringReader(plainXML); 
		 Log.d("XML",plainXML);
		 XMLDayPOJO day = serializer.read(XMLDayPOJO.class, reader);
		 return day;
	 }
	 
	 private String getPlainXMLString(String url, int option) throws HttpException
	 {
		 //first lookup preferences if wanted
		 SharedPreferences preferences = context.getSharedPreferences("EatData", Context.MODE_PRIVATE);
		 if(option == XMLProvider.OPTION_CACHE)
		 {
			 if(preferences.contains(url))
			 {
				 Log.d("getPlainXMLString","from preferences");
				 return preferences.getString(url, "");
			 }
		 }
		 Log.d("getPlainXMLString","from web");
		 
		 //check online state
		 final NetworkInfo network =  ((ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
		 if( network != null && network.getState() == NetworkInfo.State.CONNECTED )
		 {
	
			 
			 //now try to get data
			 HttpGet getRequest = new HttpGet(url);
			 try {
				HttpResponse getResponse = client.execute(getRequest);
				final int statusCode = getResponse.getStatusLine().getStatusCode();  
				if(statusCode != HttpStatus.SC_OK)
				{
					throw new HttpException("Statuscode vom Server nicht OK.");
				}
				
				HttpEntity getResponseEntity = getResponse.getEntity(); 
				if(getResponseEntity == null)
				{
					throw new HttpException("Server antwortet nicht.");
				}
				
				String xml=EntityUtils.toString(getResponseEntity);
				SharedPreferences.Editor editor = preferences.edit();
				editor.putString(url, xml);
				editor.commit();
				
				return xml; 
				
			} catch (ClientProtocolException e) {
				e.printStackTrace();
				throw new HttpException("Server versteht mich nicht.");
			} catch (IOException e) {
				e.printStackTrace();
				throw new HttpException("Verbindung evtl. unterbrochen.");
			}
		 }
		 else 
		 {
			 //offline
			 //Toast.makeText(context, "offline", 2000);
			 return null;
		 }
	 }
}
